from strategy.handler.BuySeller import BuySeller


# 仅买入, 不卖出, 股票一直持有到最后
class Buyer(BuySeller):
    # 仅买计算方式相关变量
    buy2ItemCnt = 40  # 收集40(约为2个月)个交易日的数据
    buy2Collect = {}
    buy2Finish = {}
    position = {}

    def handle(self, i, signal):
        if self.buy2Collect:
            self.buyAdd()
        if not signal:
            return
        if signal[0] > 0:
            self.buy()

    def buy(self):
        """
        仅买计算方式
        """
        date = self.getDate()
        price = self.getPrice()
        self.buy2Collect[date] = [price]
        cnt = self.singleCnt
        self.log('买入,	价格:{price},买入:{cost},股数:{cnt}'
                 .format(price=price, cost=round(price * cnt, 2), cnt=cnt),
                 self.manager.tradeLogLevel)

    def buyAdd(self):
        price = self.getPrice()
        keys = list(self.buy2Collect.keys())
        for key in keys:
            self.buy2Collect[key].append(price)
            if len(self.buy2Collect[key]) >= self.buy2ItemCnt:  # 单日期收集完成
                self.buy2Finish[key] = self.buy2Collect[key]
                del self.buy2Collect[key]

    def endTrade(self):  # 结算
        rateSum = 0
        for key, val in self.buy2Finish.items():
            avg = sum(val) / len(val)
            buyPrice = val[0]
            self.inputAll += buyPrice * self.singleCnt
            self.outputAll += avg * self.singleCnt
        # rate = round((avg - buyPrice) / buyPrice, 3)
        # rateSum += rate
    # self.profitRate = rateSum / len(self.buy2Finish)
